<script setup lang="ts">
import {
  lmsSupplierConfigList,
  addlmsSupplierConfig,
  dellmsSupplierConfig,
  updatelmsSupplierConfig,
  FormlmsSupplierConfig,
  LibraryOptions,
  supplierOptions,
  inventoryTypeOptions,
  forbiddenexportStatus,
} from "@/api/DataIntegration/interface/index";
import type { RequestParams } from "@/api/DataIntegration/interface/type";
import { ElMessage, ElMessageBox } from "element-plus";
import { onMounted, reactive, ref } from "vue";
import useUserStore from "@/store/modules/user";
import dayjs from "dayjs";
let useStore = useUserStore();
const RobotList = ref([{ scheduleFlag: 1 }] as any); //列表数据

const queryFormRef = ref(); //refForm
const ids = ref([]); //表格全选
const total = ref();
const loading = ref(false);
const dialogVisible = ref(false);
const title = ref("新增");
const ruleFormRef = ref(); //弹框表单
const ruleForm = ref({
  connectInfo: [] as Array<{ key: string; value: string }>,
} as any);
const rowId = ref();
let queryParams = ref({
  pageNum: 1,
  pageSize: 10,
} as any);
const rules = reactive({
  supplierId: [{ required: true, message: "请选择供应商 ", trigger: "change" }],
  libraryId: [{ required: true, message: "请选择图书馆 ", trigger: "change" }],
  typeId: [{ required: true, message: "请选择时间类型", trigger: "change" }],
  timeName: [
    { required: true, message: "时间名称不能为空", trigger: "blur" },
    { min: 1, max: 50, message: "时间名称过长", trigger: "blur" },
  ],
  startTime: [
    { required: true, message: "请选择开始时间 ", trigger: "change" },
  ],
});
/**
 * 列表数据
 */
const getRbtList = async () => {
  try {
    const res = await lmsSupplierConfigList(queryParams.value);
    RobotList.value = res.data.records;
    total.value = res.data.total;
    console.log(res.data.records, "分页列表");
    // console.log(queryParams.value);
  } catch (error) {
    // console.error(error);
  }
};
/**
 * 重置
 */
const resetQuery = () => {
  queryFormRef.value.resetFields();
  queryParams.value = {} as RequestParams;
  queryParams.value.pageNum = 1;
  queryParams.value.pageSize = 10;
  getRbtList();
};
/**
 * 行checkbox change事件
 */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}
/**
 * 打开弹框
 */
const LibOptions = ref([] as any);
const handleSubTableOpen = async () => {
  title.value = "新增";
  dialogVisible.value = true;

  // 初始化表单
  ruleForm.value = {
    supplierName: "",
    supplierCode: "",
    connectInfo: [], // 初始化为空数组
  };

  // 其他初始化逻辑（如清空校验）
  ruleFormRef.value?.clearValidate();
  const res = await LibraryOptions(useStore.encryptedData);
  LibOptions.value = res.data;
  const ress = await inventoryTypeOptions(useStore.encryptedData);
  inventoryOptions.value = ress.data;
  // 获取供应商选项数据
  const resss = await supplierOptions(useStore.encryptedData);
  supplierOpt.value = resss.data;
};
/**
 * 关闭弹框
 */
const close = () => {
  dialogVisible.value = false;
  ruleFormRef.value.resetFields();
  ruleFormRef.value.clearValidate();
  ruleForm.value = {} as any;
};
/**
 * 处理表单提交事件
 */
const submit = async () => {
  try {
    loading.value = true;
    const isValid = await ruleFormRef.value.validate();
    if (isValid) {
      // 转换动态表单数据为对象
      const formData = {
        ...ruleForm.value,
        connectInfo: convertToObject(ruleForm.value.connectInfo),
      };

      if (title.value === "新增") {
        const res = await addlmsSupplierConfig(formData);
        if (res.code === 200) {
          ElMessage.success("新增成功");
          // 关闭对话框并重新查询列表数据
          close();
          getRbtList();
          loading.value = false;
        } else {
          ElMessage.error(res.msg);
          loading.value = false;
        }
      } else {
        const res = await updatelmsSupplierConfig(formData);
        if (res.code === 200) {
          ElMessage.success("修改成功");
          // 关闭对话框并重新查询列表数据
          close();
          getRbtList();
          loading.value = false;
        } else {
          ElMessage.error(res.msg);
          loading.value = false;
        }
      }
    }
  } catch (error) {
    console.error(error);
    loading.value = false;
  }
};

// 编辑时处理数据
const edit = async (row: any) => {
  title.value = "编辑";
  rowId.value = row.id;
  const res = await LibraryOptions(useStore.encryptedData);
  LibOptions.value = res.data;
  const { data } = await FormlmsSupplierConfig(row.id);
  // 将JSON字符串转换为数组格式
  const parseConfig = (config: string) => {
    try {
      const obj = JSON.parse(config);
      return Object.entries(obj).map(([key, value]) => ({ key, value }));
    } catch {
      return [];
    }
  };

  ruleForm.value = {
    ...data,
    connectInfo: parseConfig(data.connectInfo),
  };
  dialogVisible.value = true;
};
/**
 * 删除
 */
const dell = (row: any) => {
  const userIds = [row.id || ids.value].join(",");
  if (!userIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }
  ElMessageBox.confirm("确认删除吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async function () {
    const res = await dellmsSupplierConfig(row.id);
    if (res.code == 200) {
      getRbtList();
      ElMessage.success("删除成功");
    } else {
      ElMessage.error("删除失败");
    }
  });
};
const libraryaOpt = ref([] as any);
const supplierOpt = ref([] as any);
onMounted(async () => {
  getRbtList();
  // libOptions();

  const res = await LibraryOptions(useStore.encryptedData);
  libraryaOpt.value = res.data;
  const ress = await supplierOptions(useStore.encryptedData);
  supplierOpt.value = ress.data;

  console.log(ress, " ress");
});
const handleSizeChange = (val: number) => {
  queryParams.value.pageSize = val;
  queryParams.value.pageNum = 1;

  getRbtList();
};
const handleCurrentChange = (val: number) => {
  queryParams.value.pageNum = val;
  getRbtList();
  window.scrollTo({ top: 0, behavior: "smooth" }); // 立即回到顶部，并使用平滑滚动效果
};
// 控制序号
const indexMethod = (index: any) => {
  // 1、index:代表当前行数据的下标
  // 2、下标+1:  分页不要纠结：这块不是业务，完全是数学问题！
  return (
    index + 1 + (queryParams.value.pageNum - 1) * queryParams.value.pageSize
  );
};

// 处理提交时的数据转换
const convertToObject = (arr: Array<{ key: string; value: string }>) => {
  return arr.reduce((acc: Record<string, string>, item) => {
    if (item.key) acc[item.key] = item.value;
    return acc;
  }, {});
};
/**
 * 修改状态
 */

function handleStatusChange(row: { [key: string]: any }) {
  const text = row.scheduleFlag === 1 ? "启用" : "关闭";
  ElMessageBox.confirm("确认要" + text + "定时同步吗?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      return forbiddenexportStatus({
        id: row.id,
        scheduleFlag: row.scheduleFlag,
      });
    })
    .then(() => {
      ElMessage.success(text + "成功");
    })
    .catch(() => {
      row.scheduleFlag = row.scheduleFlag === 1 ? 0 : 1;
    });
}
const formatDateTime = () => {
  const formattedDateTime = dayjs(ruleForm.value.startTime).format(
    "YYYY-MM-DD HH:mm:ss"
  );
  ruleForm.value.startTime = formattedDateTime;
};
const inventoryOptions = ref([] as any);
// 根据供应商选择变化处理连接信息回显
const handleSupplierChange = (supplierId: string) => {
  // 清空现有连接信息
  ruleForm.value.connectInfo = [];

  // 找到选中的供应商
  const selectedSupplier = supplierOpt.value.find(
    (item: any) => item.id === supplierId
  );
  if (!selectedSupplier?.formConfig) return;

  try {
    // 解析 formConfig（可能是字符串或对象）
    const formConfig =
      typeof selectedSupplier.formConfig === "string"
        ? JSON.parse(selectedSupplier.formConfig)
        : selectedSupplier.formConfig;

    // 递归提取所有键名
    const extractAllKeys = (obj: any): string[] => {
      const keys: string[] = [];
      for (const key in obj) {
        if (typeof obj[key] === "object" && obj[key] !== null) {
          keys.push(...extractAllKeys(obj[key])); // 递归处理嵌套对象
        } else {
          keys.push(key); // 添加当前层级的键
        }
      }
      return keys;
    };

    // 获取所有唯一键名
    const allKeys = [...new Set(extractAllKeys(formConfig))];

    // 生成键值对
    allKeys.forEach((key) => {
      ruleForm.value.connectInfo.push({
        key, // 显示所有键名
        value: "", // 值留空
      });
    });
  } catch (error) {
    console.error("解析 formConfig 失败", error);
  }
};
</script>

<template>
  <div class="app-container">
    <div class="search">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="LMS供应商">
          <el-select
            v-model="queryParams.supplierId"
            placeholder="请选择LMS供应商"
            style="width: 200px"
          >
            <el-option
              v-for="item in supplierOpt"
              :key="item.value"
              :label="item.supplierName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="图书馆">
          <el-select
            v-model="queryParams.libraryId"
            placeholder="请选择图书馆"
            style="width: 200px"
          >
            <el-option
              v-for="item in libraryaOpt"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="getRbtList">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
          <el-button @click="handleSubTableOpen">添加</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-card>
      <template #header>
        <!-- <el-button type="danger" :disabled="ids.length === 0" @click="dell"
          >删除</el-button
        > -->
      </template>
      <el-table
        v-loading="loading"
        highlight-current-row
        :data="RobotList"
        :border="true"
        @selection-change="handleSelectionChange"
      >
        <!-- <el-table-column type="selection" width="55" :align="'center'" /> -->
        <el-table-column
          type="index"
          width="80"
          label="序号"
          :align="'center'"
          :index="indexMethod"
        />
        <el-table-column
          label="图书馆名称"
          prop="libraryName"
          :align="'center'"
        />
        <el-table-column
          label="LMS供应商"
          prop="supplierName"
          :align="'center'"
        />
        <el-table-column
          label="连接信息"
          :align="'center'"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <pre style="margin: 0">{{ row.connectInfo }}</pre>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <el-switch
              v-if="scope.row.scheduleFlag !== undefined"
              v-model="scope.row.scheduleFlag"
              :inactive-value="0"
              :active-value="1"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column
          label="定时规则"
          prop="cronExpression"
          :align="'center'"
        />
        <el-table-column label="创建时间" prop="createTime" :align="'center'" />
        <el-table-column
          fixed="right"
          label="操作"
          :align="'center'"
          width="220"
        >
          <template #default="{ row }">
            <el-button type="primary" link size="small" @click="edit(row)"
              >编辑</el-button
            >
            <el-button type="primary" link size="small" @click="dell(row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="margin-top: 15px"
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 30, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
    <el-dialog
      v-model="dialogVisible"
      :title="title"
      width="600px"
      @close="close"
    >
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="100px"
        status-icon
      >
        <el-form-item label="图书馆" prop="libraryId" ref="libraryref">
          <el-select v-model="ruleForm.libraryId" placeholder="请选择图书馆">
            <el-option
              v-for="item in LibOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="供应商" prop="supplierId" ref="supplierIdref">
          <el-select
            v-model="ruleForm.supplierId"
            placeholder="请选择供应商"
            @change="handleSupplierChange"
          >
            <el-option
              v-for="item in supplierOpt"
              :key="item.value"
              :label="item.supplierName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="开始时间"
          prop="startTime"
          style="width: 100%; white-space: nowrap"
        >
          <el-date-picker
            v-model="ruleForm.startTime"
            type="datetime"
            format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择时间"
            @change="formatDateTime"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="时间类型" prop="typeId">
          <el-select v-model="ruleForm.typeId" placeholder="请选择时间类型">
            <el-option
              v-for="item in inventoryOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="定时规则"
          prop="supplierName"
          style="white-space: nowrap"
        >
          <el-input
            v-model="ruleForm.cronExpression"
            placeholder="请输入定时规则"
          />
        </el-form-item>

        <el-form-item label="连接信息">
          <div
            v-for="(item, index) in ruleForm.connectInfo"
            :key="index"
            class="key-value-item"
          >
            <el-input
              v-model="item.key"
              placeholder="键"
              style="width: 200px; margin-right: 10px"
            />
            <el-input
              v-model="item.value"
              placeholder="值"
              style="width: 200px; margin-right: 10px"
            />
            <!-- <el-button
              type="danger"
              @click="removeKeyValue('connectInfo', index)"
              icon="Delete"
              circle
              plain
            /> -->
          </div>
          <!-- <el-button type="primary" plain @click="addKeyValue('connectInfo')">
            添加配置项
          </el-button> -->
        </el-form-item>
        <el-form-item label="定时同步" prop="status">
          <el-radio-group v-model="ruleForm.scheduleFlag">
            <el-radio :value="1">是</el-radio>
            <el-radio :value="0">否</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submit">确 定</el-button>
          <el-button @click="close">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
* {
  list-style: none;
}

el-select {
  padding-bottom: 100px;
}

.key-value-item {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}
</style>
